package com.rabbitClient.pointToPoint;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Producer {

	public static final String QUEUE_NAME = "rabbitClient.queue";
	public static final String HOST = "192.168.1.219";
	public static final String USER = "guest";
	public static final String PASSWORD = "guest";
	public static final int PORT = 5672;
	public static final String VIRTUAL_HOST = "test";

	public static void main(String[] args) throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(HOST);
		factory.setPort(PORT);
		factory.setUsername(USER);
		factory.setPassword(PASSWORD);
		factory.setVirtualHost(VIRTUAL_HOST);

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		/*
		 * 第一个参数为队列名 第二个参数为是否持久化（队列在服务器重启后继续存在） 第三个参数为是否独占队列
		 * 第四个参数为是否自动删除队列（服务器不再使用时将其删除） 第五个为参数队列的其他属性
		 **/
		// 声明一个队列（如果此队列没有创建者创建）
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		// 开启确认模式
		channel.confirmSelect();

		String message = "hello RabbitMQ";
		// 在channel上添加监听
		channel.addConfirmListener(new ConfirmListener() {

			@Override
			public void handleAck(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("消息确认发送成功：deliveryTag");

			}

			@Override
			public void handleNack(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("消息发送失败");

			}

		});
		// 发送消息到队列中
		String newMessage;
		for (int i = 0; i < 10; i++) {
			newMessage = message + i;
			channel.basicPublish("", QUEUE_NAME, null, newMessage.getBytes("UTF-8"));
		}

		// 关闭通道和连接
//		channel.close();
//		connection.close();
	}
}
